package day05;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.TimeUnit;

/**
 * 基于数组实现的FIFO的阻塞队列,初始化需要指定最大容量,支持泛型
 */
public class ArrayBlockingQueueExample01 {

    public static void main(String[] args) {
        ArrayBlockingQueue<String> blockingQueue = new ArrayBlockingQueue<>(2);
        // 阻塞式写入
        new Thread(() -> {
            try {
                blockingQueue.put("a");
                blockingQueue.put("b");
                blockingQueue.offer("c", 5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        // 阻塞式读取
        new Thread(() -> {
            try {
                System.out.println(blockingQueue.take());
                System.out.println(blockingQueue.take());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        // 非阻塞式写法
        new Thread(() -> {
            blockingQueue.add("d");
            blockingQueue.offer("e");
            try {
                blockingQueue.add("f");
            } catch (Exception e) {
                System.out.println("突出");
            }
        }).start();
        // 非阻塞式读取
        new Thread(() -> {
            System.out.println(blockingQueue.poll());
            System.out.println(blockingQueue.poll());
            assert blockingQueue.poll() == null;
        }).start();
    }

}
